<template>
	<div class="eltable-batch-add" :class="[`is-scroll-${scrollStatus}`]" id="el-batch-add-id"
		:style="{ height: filterHeight(height) }" @scroll="onScroll">
		<table cellspacing="0">
			<thead>
				<tr>
					<template v-for="(item, index) in titleList" :key="index">
						<th :class="[item.fixed ? 'th-fixed-' + item.fixed : '']" :style="{
							width: filterWidth(item, titleList),
						}">
							{{ item.title }}
						</th>
					</template>
				</tr>
			</thead>
			<tbody>
				<tr v-for="(row, index) in dataList" :key="index">
					<template v-for="(citem, cindex) in titleList" :key="cindex">
						<td :class="[citem.fixed ? 'td-fixed-' + citem.fixed : '']" :style="{
							width: filterWidth(citem, titleList),
						}">
							<slot :name="citem.slot" v-bind="{ row, index }">
								<span v-if="citem.type === 'index'">
									{{ index + 1 }}
								</span>
								<el-input v-else clearable v-model="row[citem.key]" placeholder="请输入"></el-input>
							</slot>
						</td>
					</template>
				</tr>
			</tbody>
		</table>
		<el-empty v-if="dataList.length === 0" style="height: calc(100% - 40px)" description="暂无数据"></el-empty>
	</div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'

const props = defineProps({
	height: {
		type: [String, Number],
		default: 500,
	},
	formData: {
		type: Object,
		default: () => { },
	},
	titleList: {
		type: Array,
		default: () => [],
	}
})
const dataList = ref([])
const scrollStatus = ref('')

const onScroll = (e) => {
	const { scrollLeft, scrollWidth, clientWidth } = e.target;
	const distance = scrollWidth - clientWidth;
	if (scrollLeft === 0) {
		scrollStatus.value = 'left'
	} else if (scrollLeft === distance) {
		scrollStatus.value = 'right'
	} else {
		scrollStatus.value = 'middle'
	}
}
//高度
const filterHeight = (val) => {
	return val.toString().includes("px") ? val : val + "px";
}
//设置元素宽度
const filterWidth = (item, list) => {
	if (item.width) {
		return item.width + "px";
	}
	let allNum = list.length;
	let arr = list.filter((l) => {
		return l.width !== undefined;
	});
	let num = allNum - arr.length;
	let kownWidth = 0;
	arr.forEach((a) => {
		kownWidth += a.width;
	});
	let width = `calc((100% - ${kownWidth}px)/${num} - 20px)`;
	return width;
}
//添加行
const onBatchAdd = () => {
	let obj = JSON.parse(JSON.stringify(props.formData));
	dataList.value.push(obj);
	nextTick(() => {
		let div = document.getElementById("el-batch-add-id");
		div.scrollTop = div.scrollHeight;
	});
}
//删除行
const onDeleteRow = (index) => {
	dataList.value.splice(index, 1);
}
//保存数据
const onSaveForm = () => {
	return dataList.value;
}
defineExpose({
	onBatchAdd,
	onDeleteRow,
	onSaveForm
})
</script>
<style lang="less" scoped>
@import "./batchAdd.less";
</style>
